﻿using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Search.ElasticSearch.Event;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System;

namespace NHibernate.Search.ElasticSearch.Cfg
{
    public static class ConfigurationExtensions
    {
        private static IDictionary<string, NHibernateSearchConfiguration> cfgs = new Dictionary<string, NHibernateSearchConfiguration>();

        internal static void AddNHibernateSearchConfiguration(NHibernateSearchConfiguration cfg)
        {
            cfgs.Add(cfg.Index, cfg);
        }
        internal static NHibernateSearchConfiguration GetNHibernateSearchConfiguration(string sessionFacotoryName)
        {
            return cfgs[sessionFacotoryName];
        }
        public static Configuration ConfigureFullTextSearch(this Configuration cfg)
        {
            string cfgXmlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs/Hibernate-Search.cfg.xml");
            if (File.Exists(cfgXmlFile))
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(cfgXmlFile);
                foreach (XmlNode xmlNode in xmlDocument.DocumentElement.FirstChild.ChildNodes)
                {
                    cfg.Properties.Add(xmlNode.Attributes["name"].Value, xmlNode.InnerText);
                }
                cfg.SetListener(ListenerType.PostInsert, new FullTextIndexEventListener());
                cfg.SetListener(ListenerType.PostUpdate, new FullTextIndexEventListener());
                cfg.SetListener(ListenerType.PostDelete, new FullTextIndexEventListener());
            }
            return cfg;
        }


    }
}
